import Flutter
import UIKit

@main
@objc class AppDelegate: FlutterAppDelegate {
    var fileChannel: FlutterMethodChannel?
    var url_path : String?
    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        // 确保其他插件的注册
        GeneratedPluginRegistrant.register(with: self)
        // 获取 FlutterViewController
        if let flutterViewController = window?.rootViewController as? FlutterViewController
        {
            // 创建 MethodChannel
            fileChannel = FlutterMethodChannel(name: "com.dsp18/file", binaryMessenger: flutterViewController.binaryMessenger)
        }
        
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }
    
    // 处理外部应用打开文件《这里是： 应用外启动app，flutter 主动向iOS询问文件内容，iOS被动向flutter传递文件内容》
    override func application(
        _ application: UIApplication,
        open url: URL,
        options: [UIApplication.OpenURLOptionsKey : Any] = [:]
    ) -> Bool {
        // 检查是否已初始化 MethodChannel，《flutter 主动向iOS询问文件内容，iOS被动向flutter传递文件内容》
        fileChannel?.setMethodCallHandler {[weak self] (call: FlutterMethodCall, result: @escaping FlutterResult) in
            if call.method == "getFileUri" {
                // 处理从 Flutter 端的请求，例如返回模拟的文件路径
                self?.url_path = url.path
                result(url.path);
            } else {
                result(FlutterMethodNotImplemented)
            }
        }
        
        /// invokeMethod == > 《flutter被动监听，iOS主动向flutter 传递文件内容》
        fileChannel?.invokeMethod("getFileUri", arguments: url.path)        
        return true
    }
}


